package com.novel.framework.satoken;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.util.ObjectUtil;
import com.novel.system.domain.LoginUser;
import com.novel.system.service.SysMenuService;
import com.novel.system.service.SysRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * sa-token 权限管理实现类
 *
 * @author Lion Li
 */
@Component
@RequiredArgsConstructor
public class SaPermissionImpl implements StpInterface {

    private final SysMenuService sysMenuService;
    private final SysRoleService sysRoleService;

    /**
     * 获取菜单权限列表
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        LoginUser loginUser = LoginHelper.getLoginUser();

        if (ObjectUtil.isNotNull(loginUser)) {
            if (loginUser.getUser().isAdmin()) {
                List<String> list = new ArrayList<>();
                // 管理员拥有所有权限
                list.add("*:*:*");
                return list;
            } else {
                return sysMenuService.selectPermsByUserId(loginUser.getUser().getId()).stream().toList();
            }
        }
        return new ArrayList<>();
    }

    /**
     * 获取角色权限列表
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (ObjectUtil.isNotNull(loginUser)) {
            if (loginUser.getUser().isAdmin()) {
                List<String> list = new ArrayList<>();
                // 管理员拥有所有权限
                list.add("admin");
                return list;
            } else {
                return sysRoleService.selectRoleKeys(loginUser.getUser().getId()).stream().toList();
            }
        }
        return new ArrayList<>();
    }
}
